package com.itheima.mp.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mp.domain.enums.UserStatus;
import com.itheima.mp.domain.po.User;
import com.itheima.mp.mapper.UserMapper;
import com.itheima.mp.service.IUserService;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    public void deductBalance(Long id, Integer money) {
        // 判断用户状态是否正常
        User user = getById(id);
        if(user == null || user.getStatus() != UserStatus.NORMAL)
            throw new RuntimeException("用户不存在或状态异常");
        // 判断账户余额是否充足
       if(user.getBalance() < money)
           throw new RuntimeException("账户余额不足");
        // 扣减余额
        int remainBalance = user.getBalance() - money;
        lambdaUpdate()
                .set(User::getBalance, remainBalance)
                .set(remainBalance == 0, User::getStatus, 2)
                .eq(User::getId, id)
                .update();
    }
}

